<?php
namespace app\admin\controller;

// 引用后台公共控制器
use app\common\controller\Backend;
// 引用验证码的类
use think\captcha\Captcha;
use think\Db;

class Index extends Backend
{
    // 不需要的登录数组
    protected $NoNeedLogin = ['login','logout','captcha'];

    public function __construct()
    {
        parent::__construct();

        // 引用admin模型
        $this->AdminModel = model('Admin');
    }
    public function index()
    {
        $title = '后台首页';

        $UserCount = model('User.User')->count();

        $OrderCount = model('Product.Order')->count();

        $PostCount = model('Post.Post')->count();

        $PayCount = model('Product.Pay')->where('status',1)->sum('point');

        $cateList = model('Post.Cate')->order('weigh','asc')->field('id,name')->select();

        // 重组一个分类数组
        $CateList = array_column($cateList,'name');

        // 已采纳
        $AcceptList = [];
        // 未采纳数组
        $NotAcceptList = [];

        foreach($cateList as $item)
        {
            //查询出每个分类中已采纳和未采纳的总数
            //已采纳
            $where1 = [
                'cateid' => $item['id'],
                'accept' => ['exp',Db::raw('is not null')]
            ];

            $AcceptList[] = model('Post.Post')->where($where1)->count();

            // 未采纳
            $where2 = [
                'cateid' => $item['id'],
                'accept' => ['exp',Db::raw('is null')]
            ];

            $NotAcceptList[] = model('Post.Post')->where($where2)->count();
            
        }

        // halt($NotAcceptList);
        $this->assign([
            'title' => $title,
            'UserCount' => $UserCount,
            'OrderCount' => $OrderCount,
            'PostCount' => $PostCount,
            'PayCount' => $PayCount,
            'CateList' => json_encode($CateList),
            'AcceptList' => json_encode($AcceptList),
            'NotAcceptList' => json_encode($NotAcceptList)
        ]);
        return $this->fetch();
    }

    // 登录
    public function login()
    {
        // 临时关闭当前模板的布局功能
        $this->view->engine->layout(false);

        // 获取session
        $LoginAdmin = session('LoginAdmin');

        if(!empty($LoginAdmin))
        {
            $admin = $this->AdminModel->where('id',$LoginAdmin['id'])->find();

            // dump($admin);
            if(!$admin)
            {
                session('LoginAdmin',null);
                $this->error('非法登录',url('admin/index/login'));
                exit;
            }

            if($admin['state'] != 1)
            {
                session('LoginAdmin',null);
                $this->error('该用户异常，请重新输入',url('admin/index/login'));
                exit;
            }

            $this->success('你已经登录成功了，无需重新登录',url('admin/index/index'));
            exit;

        }
        
        if($this->request->isPost())
        {
            // 接收全部参数
            $params = $this->request->param();
            
            // halt($params);

            // 判断验证码是否正确
            if(!captcha_check($params['captcha']))
            {
                $this->error('验证码输入错误',url('admin/index/login'));
                exit;
            }

            $admin = $this->AdminModel->where(['username' => $params['username']])->find();

            // 用户是否存在
            if(!$admin)
            {
                $this->error('该用户不存在，请重新输入',url('admin/index/login'));
                exit;
            }

            // 获取密码盐
            $salt = $admin['salt'];

            // 接收的密码跟密码盐拼接并且加密
            $password = md5($params['password'] . $salt);
            
            // 密码是否正确
            if($password != $admin['password'])
            {
                $this->error('密码输入错误，请重新输入',url('admin/index/login'));
                exit;
            }

            // 用户是否正常
            if($admin['state'] != 1)
            {
                $this->error('该用户异常，请重新输入',url('admin/index/login'));
                exit;
            }

            $LoginAdmin = [
                'id' => $admin['id'],
                'nickname' => $admin['nickname']
            ];

            // 把登录的用户存到session
            session('LoginAdmin',$LoginAdmin);

            // 跳转到后台首页
            $this->success('登录成功',url('admin/index/index'));
        }

        return $this->fetch();
    }

    // 退出
    public function logout()
    {
        // 清除session
        session('LoginAdmin',null);

        // 跳转到后台登录
        $this->success('退出成功',url('admin/index/login'));
        exit;
    }

    // 配置验证码
    public function captcha()
    {
        $config = [
            'length' => 4,
            'imageW' => 120,
            'imageH' => 40,
            'fontSize' => 18
        ];

        $captcha = new Captcha($config);
        return $captcha->entry();
    }

     //回收站页面
     public function recycle(){

        $keywords = $this->request->param('keywords', '');
        $start = $this->request->param('start', '');
        $end = $this->request->param('end', '');

        $where = [];

        //关键字
        if(!empty($keywords)){

            $where['title'] = ['like',"%$keywords%"];

        }

        //判断开始时间是否为空
        if(!empty($start))
        {
            //标准时间转化为时间戳
            $starttime = strtotime($start);
            $where['createtime'] = ['EGT', $starttime];
        }

        if(!empty($end))
        {
            //标准时间转化为时间戳
            $endtime = strtotime($end);
            $where['createtime'] = ['ELT', $endtime];
        }

        //总数
        $count = $this->PostModel->onlyTrashed()->count();
      
        $postlist = $this->PostModel->onlyTrashed()->where($where)->order('createtime','desc')->paginate(10);

        $pagestr = $postlist->render();

        // var_dump($postlist);
        // exit;

        $this->assign([
            'count'=> $count,
            'postlist'=> $postlist,
            'pagestr'=> $pagestr,
            'keywords' => $keywords,
            'start' => $start,
            'end' => $end,
        ]);
        return $this->fetch();
    }
}